package aa.maven.me_reptile.base;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebClientOptions;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

/**
 * 模拟浏览器处理url
 *
 */
public class HtmlReptile {
	
	private HtmlPage page;
	
	/**
	 * 可以模拟的浏览器有三种
	 * FIREFOX_24、INTERNET_EXPLORER_11、CHROME
	 *
	 * @param url 请求地址
	 * @throws IOException 
	 * @throws MalformedURLException 
	 * @throws FailingHttpStatusCodeException 
	 */
	public HtmlReptile(String url) throws FailingHttpStatusCodeException, IOException{
		WebClient webClient = new WebClient(BrowserVersion.CHROME);
		//参数设置
		WebClientOptions webClientOptions = webClient.getOptions();
		webClientOptions.setJavaScriptEnabled(true); //启动js解析器
		webClientOptions.setCssEnabled(false);//禁止css支持
		webClientOptions.setThrowExceptionOnScriptError(false);//js异常是否抛出
		webClientOptions.setTimeout(10000);

		page=webClient.getPage(url);
	}
	/**
	 * 根据指定表达式获取元素
	 * @param pattern 如：//div[@id='blog_owner_name']  
	 * 			/html/body/div[2]/div[2]/div/div[16]/div/h3/a
	 * @return
	 */
	public List<HtmlDivision> getElementByPattern(String pattern){
		return  page.getByXPath(pattern);
	}
	
	/**
	 * 根据Id获取元素
	 * @param id
	 * @return
	 */
	public HtmlDivision getElementById(String id){
		return page.getHtmlElementById(id);
	}
	
	public String getText(){
		return page.asText();
	}
	public String getElements(){
		return page.asXml();
	}

}
